package org.jradweb.tools.generator.hibernate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.maven.plugin.logging.Log;
import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.jradweb.tools.generator.utils.LogImpl;
import org.jradweb.tools.generator.utils.PropertiesLoader;

/**
 * Utils for Hbm to DLL and database
 *
 * Created On 2008-3-4
 * @author <a href="mailto:wagzhi@gmail.com">Paul Wang</a>
 * @version $Id: Hbm2DDL.java 104 2008-04-16 02:32:27Z wagzhi $
 */
public class Hbm2DDL {
	private File baseDir;
	private Log log;
	public Hbm2DDL(File baseDir,Log log){
		this.baseDir=baseDir;
		this.log=log;
	}
	public void toDDL(){
		try {
			Configuration config=new AnnotationConfiguration();
			this.getLog().info("config: "+config);
			File cfg=new File(this.getBaseDir().getAbsolutePath()+"/src/main/resources/hibernate.cfg.xml");
			config=config.configure(cfg);
			PropertiesLoader pl=new PropertiesLoader(this.getBaseDir());
			java.util.Properties props=pl.loadProjectProperties();
			config.setProperty("hibernate.connection.username", props.getProperty(PropertiesLoader.DATABASE_USER_NAME) );
			config.setProperty("hibernate.connection.password",props.getProperty(PropertiesLoader.DATABASE_PASSWORD));
			config.setProperty("hibernate.connection.url", props.getProperty(PropertiesLoader.DATABASE_URL));
			config.setProperty("hibernate.connection.driver_class", props.getProperty(PropertiesLoader.DATABASE_DRIVER_CLASS_NAME));
			config.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
			
			SchemaExport export = new SchemaExport( config );
			File outputFile=new File(this.getBaseDir().getAbsolutePath()+"/src/main/config/db/script.sql");
			if(!outputFile.exists()){
				File folder=outputFile.getParentFile();
				if(!folder.exists())
					folder.mkdirs();
				outputFile.createNewFile();
			}
			export.setOutputFile(outputFile.getAbsolutePath());
			export.create(true, true);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public Log getLog() {
		return log;
	}
	public void setLog(Log log) {
		this.log = log;
	}
	public File getBaseDir() {
		return baseDir;
	}
	public void setBaseDir(File baseDir) {
		this.baseDir = baseDir;
	}
	public static void main(String[] args){
		File projectRootPath = new File("D:/workspace2/jradtest");
		LogImpl log=new LogImpl(Hbm2DDL.class);
		Hbm2DDL h2d=new Hbm2DDL(projectRootPath,log);
		
		h2d.toDDL();
	}
}
